﻿using System.Collections.Generic;
using System.IO;

namespace Domain.Models
{
    public class VariantsWorker
    {
        private readonly IRepository<Variant> repository;
        private readonly Dictionary<long, string> idPathdictionary;
        private readonly string variantsDirectoryPath = Directory.GetCurrentDirectory()+@"\Variants\";
        private const string MillitaryExtension = ".millitary";

        public VariantsWorker(IRepository<Variant> repository)
        {
            this.repository = repository;
            idPathdictionary=new Dictionary<long, string>();
        }

        public List<Variant> LoadAllVariants()
        {
            var variants = new List<Variant>();
            idPathdictionary.Clear();

            if (Directory.Exists(variantsDirectoryPath) == false)
                return variants;

            var fileNames = Directory.GetFiles(variantsDirectoryPath);
            foreach (var fileName in fileNames)
            {
                if (new FileInfo(fileName).Extension != MillitaryExtension) continue;

                var variant = repository.Load(fileName);
                if (variant == null) continue;
                
                variants.Add(variant);
                idPathdictionary.Add(variant.Id,fileName);
            }
            return variants;
        }

        public void SaveVariant(Variant variant)
        {
            if (Directory.Exists(variantsDirectoryPath) == false)
                Directory.CreateDirectory(variantsDirectoryPath);

            if (idPathdictionary.ContainsKey(variant.Id) == true)
                repository.Save(variant, idPathdictionary[variant.Id]);
            else
            {
                var fileName = variantsDirectoryPath + variant.Id.ToString() + MillitaryExtension;
                idPathdictionary.Add(variant.Id,fileName);
                repository.Save(variant, fileName);
            }
        }

        public void DeleteVariant(Variant  variant)
        {
            if (idPathdictionary.ContainsKey(variant.Id))
                File.Delete(idPathdictionary[variant.Id]);
        }
    }
}